package view.chart;

import java.awt.Color;
import java.sql.SQLException;
import java.sql.Time;
import java.util.List;

import javax.swing.JFrame;
import javax.swing.JPanel;

import misc.Util;
import model.bean.Cenario;
import model.dao.CenarioDAO;

import org.jfree.chart.ChartFactory;
import org.jfree.chart.ChartPanel;
import org.jfree.chart.JFreeChart;
import org.jfree.chart.axis.NumberAxis;
import org.jfree.chart.plot.CategoryPlot;
import org.jfree.chart.plot.PiePlot3D;
import org.jfree.chart.plot.PlotOrientation;
import org.jfree.chart.renderer.category.BarRenderer;
import org.jfree.data.category.CategoryDataset;
import org.jfree.data.category.DefaultCategoryDataset;
import org.jfree.data.general.DefaultPieDataset;

public class CenarioChart{
	private CenarioChart(){
//		CategoryDataset dataset = createDataset();
//		JFreeChart chart = createChart(dataset);
//		ChartPanel chartPanel = new ChartPanel(chart);
//		chartPanel.setPreferredSize(new Dimension(800, 600));		
	}
	
	private static CategoryDataset createQuantidadePorUsuarioDataset(String aplicacaoNome, String startPeriod, String endPeriod){
		try{
			DefaultCategoryDataset dataset = new DefaultCategoryDataset();
			List<Cenario> cenarios = CenarioDAO.queryQuantidadePorUsuario(aplicacaoNome, startPeriod, endPeriod);
			for(Cenario cenario : cenarios){
				dataset.addValue(Double.parseDouble(cenario.getNome()), "Quantidade de cenários concluídos por usuário", cenario.getIdsessao());			
			}
			return dataset;
		}catch(NullPointerException e){
			e.printStackTrace();
		}catch(SQLException e){
			e.printStackTrace();
		}
		return null;
	}
	
	private static JFreeChart createQuantidadePorUsuarioChart(CategoryDataset dataset){
		JFreeChart chart = ChartFactory.createBarChart3D(
				"Quantidade de Cenários Concluídos por Usuário", // Titulo do grafico
				"Usuários", // Titulo do eixo x
				"Quantidade de Cenários", // Titulo do eixo y
				dataset, // dados
				PlotOrientation.VERTICAL, // orientacao
				true, // incluir legenda
				true, // incluir hint
				false // incluir URLs
				);
		chart.setBackgroundPaint(Color.WHITE);
		CategoryPlot categoryPlot = chart.getCategoryPlot();
		categoryPlot.setBackgroundPaint(Color.LIGHT_GRAY);
		categoryPlot.setDomainGridlinePaint(Color.WHITE);
		categoryPlot.setRangeGridlinePaint(Color.WHITE);
		NumberAxis rangeAxis = (NumberAxis) categoryPlot.getRangeAxis();
		rangeAxis.setUpperMargin(0.15);
		BarRenderer barRenderer = (BarRenderer)categoryPlot.getRenderer();
		barRenderer.setSeriesPaint(0, new Color(0, 0, 120));
		categoryPlot.setForegroundAlpha(0.80f);
		
		return chart;
	}
	
	public static JPanel createQuantidadePorUsuarioPanel(String aplicacaoNome, String startPeriod, String endPeriod){
		JFreeChart chart = createQuantidadePorUsuarioChart(createQuantidadePorUsuarioDataset(aplicacaoNome, startPeriod, endPeriod));
		return new ChartPanel(chart);
	}
	
	private static CategoryDataset createTempoMedioDataset(String aplicacaoNome, String startPeriod, String endPeriod){
		try{
			DefaultCategoryDataset dataset = new DefaultCategoryDataset();
			List<Cenario> cenarios = CenarioDAO.queryTempoMedio(aplicacaoNome, startPeriod, endPeriod);
			for(Cenario cenario : cenarios){
				Time duracao = cenario.getDuracao();
				if(duracao != null){
					dataset.addValue(Util.timeToSeconds(duracao), "Tempo médio dos Cenários", cenario.getNome() + " - " + duracao.toString());
				}
			}
			return dataset;
		}catch(NullPointerException e){
			e.printStackTrace();
		}catch(SQLException e){
			e.printStackTrace();
		}
		return null;
	}
	
	private static JFreeChart createTempoMedioChart(CategoryDataset dataset){
		JFreeChart chart = ChartFactory.createBarChart3D(
				"Tempo médio dos Cenários", // Titulo do grafico
				"Cenários", // Titulo do eixo x
				"Tempo médio dos Cenários em segundos", // Titulo do eixo y
				dataset, // dados
				PlotOrientation.VERTICAL, // orientacao
				true, // incluir legenda
				true, // incluir hint
				false // incluir URLs
				);
		chart.setBackgroundPaint(Color.WHITE);
		CategoryPlot categoryPlot = chart.getCategoryPlot();
		categoryPlot.setBackgroundPaint(Color.LIGHT_GRAY);
		categoryPlot.setDomainGridlinePaint(Color.WHITE);
		categoryPlot.setRangeGridlinePaint(Color.WHITE);
		NumberAxis rangeAxis = (NumberAxis) categoryPlot.getRangeAxis();
		rangeAxis.setUpperMargin(0.15);
		BarRenderer barRenderer = (BarRenderer)categoryPlot.getRenderer();
		barRenderer.setSeriesPaint(0, new Color(0, 0, 120));
		categoryPlot.setForegroundAlpha(0.80f);
		
		return chart;
	}
	
	public static JPanel createTempoMedioPanel(String aplicacaoNome, String startPeriod, String endPeriod){
		JFreeChart chart = createTempoMedioChart(createTempoMedioDataset(aplicacaoNome, startPeriod, endPeriod));
		return new ChartPanel(chart);
	}
	
	
	private static DefaultPieDataset createTempoMedioPieDataset(String aplicacaoNome, String startPeriod, String endPeriod){
		try{
			DefaultPieDataset dataset = new DefaultPieDataset();
			List<Cenario> cenarios = CenarioDAO.queryTempoMedio(aplicacaoNome, startPeriod, endPeriod);
			for(Cenario cenario : cenarios){
				Time duracao = cenario.getDuracao();
				if(duracao != null){
					dataset.setValue(cenario.getNome(), Util.timeToSeconds(duracao));					
				}
			}
			return dataset;
		}catch(NullPointerException e){
			e.printStackTrace();
		}catch(SQLException e){
			e.printStackTrace();
		}
		return null;
	}
	
	private static JFreeChart createTempoMedioPieChart(DefaultPieDataset dataset) {
		JFreeChart chart = ChartFactory.createPieChart3D(
				"Percentual de tempo por cenário", // Titulo do grafico
				dataset, // dados
				true, // incluir legenda
				true, // incluir hint
				false // incluir URLs
				);
		chart.setBackgroundPaint(Color.WHITE);
		final PiePlot3D piePlot3D = (PiePlot3D) chart.getPlot();
		piePlot3D.setForegroundAlpha(0.60f);

		@SuppressWarnings({"unchecked", "rawtypes"})
		List<Comparable> keys = dataset.getKeys();
		if(keys.size() > 0){
			int blue = 0, value = 255 / keys.size();
			for(int i = 0; i < keys.size(); i++){
				blue = value * (i + 1);
				piePlot3D.setSectionPaint(keys.get(i), new Color(0, 0, blue));
			}
		}
		
		return chart;
	}
	
	public static JPanel createTempoMedioPiePanel(String aplicacaoNome, String startPeriod, String endPeriod){
		JFreeChart chart = createTempoMedioPieChart(createTempoMedioPieDataset(aplicacaoNome, startPeriod, endPeriod));
		return new ChartPanel(chart);
	}
	
	public static void main(String[] args){
		JFrame demo = new JFrame();
		//demo.setContentPane(CenarioChart.createQuantidadePorUsuarioPanel("Tvilo Viewer", "2012-8-7", "2012-11-1"));
		//demo.setContentPane(CenarioChart.createTempoMedioPanel("Tvilo Viewer", "2012-8-7", "2012-11-1"));
		demo.setContentPane(CenarioChart.createTempoMedioPiePanel("Tvilo Viewer", "2012-8-7", "2012-11-1"));
		demo.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		demo.pack();
		demo.setVisible(true);
	}
}